from django.conf.urls import url
from django.shortcuts import render
from rest_framework.generics import UpdateAPIView,RetrieveAPIView,RetrieveAPIView,CreateAPIView,GenericAPIView
from users.models import User
from rest_framework.response import Response
from .serializers import UserSerializer,UserDetailSerializer,UserEmailSerializer
from rest_framework.permissions import IsAuthenticated
import requests
from rest_framework.views import APIView
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from django.conf import settings



class UserNameView(GenericAPIView):
    def get(self, request, username):
        # 用户名数量查询
        count = User.objects.filter(username=username).count()



        # 返回数量
        return Response(
            {
                "username": username,
                "count": count
            }
        )



class MobileView(GenericAPIView):
    def get(self,request,mobile):
        # 手机号数量查询
        count = User.objects.filter(mobile=mobile).count()

        # 返回数量
        return Response(
            {
                "mobile":mobile,
                "count":count

            }
        )



class UserView(CreateAPIView):
    serializer_class = UserSerializer




class UserDetailView(RetrieveAPIView):
    """用户详情页"""

    serializer_class = UserDetailSerializer
    # Permission_classes = [IsAuthenticated]

    def get_object(self):
        # 重写方法，指定返回单一数据对象
        # 通过ｓelf获取请求对象
        # self.request
        return self.request.user


class UserEmailView(UpdateAPIView):
    """绑定邮箱"""
    serializer_class = UserEmailSerializer

    def get_object(self):
        return self.request.user




class VerifyEmailView(APIView):
    """发送邮箱"""

    def get(self,request):
        # 获取token值
        token = request.query_params.get("token")
        # 解密token值
        tjs = TJS(settings.SECRET_KEY,300)
        try:
            data = tjs.loads(token)
        except:
            return Response({"errors":"token值有误"},status=401)

        if not data:
            return Response({"message":"token值过期了"},status=401)

        # 获取解密后的值
        id = data["id"]
        username = data["username"]
        # 查询用户
        try:
            user = User.objects.get(id=id,username=username)

        except:
            return Response({"message":"查询用户失败"},status=401)
        # 更新激活状态
        user.email_active = True
        user.save()

        # 结果返回
        return Response({"message":"ok"})


